<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>棋局复盘</title>
</head>
    <link rel="stylesheet" href="./css/replay.css">
    <style>
        html,body {
            height: 100%;
            width: 100%;
            background-image: url(./img/create_room.png);
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
        }
    </style>
<body>

    <div id="content">
        <p style="font-size: 20px;">输入场次id，可复盘/删除对应棋局</p>
        <input type="text" id="send_msg"> <br>
        <button id="delete_button">删除对局</button> <button id="send_button">开始复盘</button>
    </div> 

    <div id="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px" style="margin-top: 20px;"></canvas>
            <!-- 显示区域 -->
            <div id="screen">复盘中... </div>
        </div>
       
        <button id="prev_step">上一步</button>
        <button id="next_step">下一步</button>
        <p id = "user_tip"></p>
    </div>

    <button id="return_hall">返回大厅</button>
    
    <div id="ranking_list">
        <h2 style=" text-align: center;">历史对战数据</h1>
       
        <table cellspacing="0px" width="500px" id="fight_table">
			<tr>
				<th>场次id</th>
				<th>执棋方</th>
				<th>对战时间</th>
				<th>对战结果</th>
			</tr>
        </table>
    </div>

    
    <script src="./js/jquery.min.js"></script>
    <script>
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess_history_data = [];
        let chess = document.getElementById('chess');
        let context = chess.getContext('2d');//获取chess控件的2d画布

        let user_color = true; //标记当前棋子颜色
        let all_step_num = 0;
        let step_flag = -1; //标记当前复盘到哪一步了
        var room_info = null;//用于保存房间信息 

        for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
        }

            for (let m = 0; m < 225; m++)
            {
                chess_history_data[m] = [];
                for (let n = 0; n < 2; n++)
                {
                    chess_history_data[m][n] = 0;
                }
            }
    
        init_replay(true);
        get_history_data();

        function init_replay(is_hidden)
        {
            var tmp1 = document.getElementById("container");       
            tmp1.hidden = is_hidden;
            var tmp2 = document.getElementById("chess_area");       
            tmp2.hidden = is_hidden;
            var tmp3 = document.getElementById("prev_step");       
            tmp3.hidden = is_hidden;
            var tmp4 = document.getElementById("next_step");       
            tmp4.hidden = is_hidden;
        }

        function loading_data_list(res, i){
            var show_div = document.getElementById("ranking_list");
            show_div.scrollTop = show_div.scrollHeight;
            var tr_div = document.createElement("tr");
            var td_div_1 = document.createElement("td");
            var tmp_1 = "fight_id_";
            tmp_1 += i;
            td_div_1.innerHTML = res[tmp_1];

            var td_div_2 = document.createElement("td");
            var tmp_2 = "fight_color_";
            tmp_2 += i;
            if (res[tmp_2] == 1)
                td_div_2.innerHTML = "黑子";
            else 
                td_div_2.innerHTML = "白子";

            var td_div_3 = document.createElement("td");
            var tmp_3 = "fight_time_";
            tmp_3 += i;
            td_div_3.innerHTML = res[tmp_3];

            var td_div_4 = document.createElement("td");
            var tmp_4 = "fight_win_";
            tmp_4 += i;
            if (res[tmp_4] != res["fight_uid"])
                td_div_4.innerHTML = "输";
            else 
                td_div_4.innerHTML = "赢";

            tr_div.appendChild(td_div_1);
            tr_div.appendChild(td_div_2);
            tr_div.appendChild(td_div_3);
            tr_div.appendChild(td_div_4);
            //将输入消息添加为子标签
            var msg_show_div = document.getElementById("fight_table");
            msg_show_div.appendChild(tr_div);
        }
        
        function initGame() {
            initBoard();
            context.strokeStyle = "#000000";
            drawChessBoard();
        }

        function initBoard() {
            var tmp1 = document.getElementById("ranking_list");
            tmp1.hidden = true;
            var tmp2 = document.getElementById("content");
            tmp2.hidden = true;
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); //横向的线条
                context.stroke();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); //纵向的线条
                context.stroke();
            }
        }

        // 悔棋-重新绘制棋盘网格线
        function drawBoardLineAgain(i, j)
        {
            context.beginPath();
            context.moveTo(15+i*30 , j*30);
            context.lineTo(15+i*30 , j*30+30);
            context.moveTo(i*30 , j*30+15);
            context.lineTo((i+1)*30 , j*30+15);
            context.stroke();
            context.closePath();
        }

        //给棋手绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#FCFCFC");
            } else {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            }
            context.fillStyle = gradient;
            context.fill();
        }

        function clear_oneStep(i, j)
        {    
            if (i < 0 || j < 0) return;
            context.clearRect(i*30, j*30, 30, 30);
            drawBoardLineAgain(i, j);
        }

        var rt_bt = document.getElementById("return_hall");
        rt_bt.onclick = function(){
            location.replace("/game_hall.html");
        }

        var prev_bt = document.getElementById("prev_step");
        prev_bt.onclick = function(){
            
            if (step_flag < 0){
                alert("已回到最初状态");
                return;
            }

            clear_oneStep(chess_history_data[step_flag][1], chess_history_data[step_flag][0]);
            step_flag--;
    
        }


        var next_bt = document.getElementById("next_step");
        next_bt.onclick = function(){
            
            if (step_flag >= all_step_num - 1)
            {
                alert("已复盘完所有棋子");
                return;
            }
            step_flag++;
            oneStep(chess_history_data[step_flag][1], chess_history_data[step_flag][0], (step_flag+1)%2);
        }
        
        function get_history_data()
        {
            $.ajax({
                url:'/data_list',
                type:'GET',
                success(res){
                    if (res.result == true)
                    {
                        for (var i = 1; i <= res.row_num; i++)
                        {
                            loading_data_list(res, i);
                        }
                    }
                    else
                    {
                        alert("获取历史数据失败");
                        location.replace("/game_hall.html");
                    }
                },
                error(xhr){
                    alert(JSON.stringify(xhr));
                }
            })
        }

        var sd_bt = document.getElementById("send_button");
        sd_bt.onclick = function(){
            
            //点击发送，获取历史数据，开始复盘
            var req_json = {
                optype: "replay",
                fight_id: document.getElementById("send_msg").value
            }

            document.getElementById("send_msg").value = "";
            //alert(JSON.stringify(req_json));

            $.ajax({
                url:'/replay',
                type:'POST',
                data: JSON.stringify(req_json),
                success(res){
                    if (res.result == true)
                    {
                        initGame();
                        init_replay(false);
                        //将棋盘数据保存起来
                        parse_history_data(res);
                        var tmp = document.getElementById("user_tip");
                        if (res["fight_color"] == 1) tmp.innerHTML = "该局您执黑子";
                        else if (res["fight_color"] == 2) tmp.innerHTML = "该局您执白子";
                        else tmp.innerHTML = "该局您是观众";
                    }
                    else
                    {
                        alert("请求信息失败，请返回大厅重试");
                    }
                },
                error(xhr){
                    alert(JSON.stringify(xhr))
                }      
            })

        }

        var db_bt = document.getElementById("delete_button");
        db_bt.onclick = function(){
            //点击发送，获取历史数据，开始复盘
            var req_json = {
                optype: "delete",
                fight_id: document.getElementById("send_msg").value
            }

            document.getElementById("send_msg").value = "";

            if (confirm("确定删除该场对局数据？") == false)
            {
                return;
            }

            $.ajax({
                url:'/replay',
                type:'POST',
                data: JSON.stringify(req_json),
                success(res){
                    if (res.result == true)
                    {
                        alert("删除成功");
                    }
                    else
                    {
                        alert("删除失败");
                    }
                },
                error(xhr){
                    alert(JSON.stringify(xhr))
                }      
            })
        }
        

        function parse_history_data(res){
            var history_data = res["fight_data"];
            var row_col_data = "";
            var op_num = 0;
            for (let i = 0; i < history_data.length; i++)
            {
                if (history_data[i] == ',')
                {
                    chess_history_data[op_num][0] = parseInt(row_col_data);
                    row_col_data = "";
                    continue;
                }
                else if (history_data[i] == ';')
                {
                    chess_history_data[op_num][1] = parseInt(row_col_data);
                    op_num++;
                    row_col_data = "";
                    continue;
                }

                row_col_data += history_data[i];
            }
            all_step_num = op_num;
        }

</script>
</body>
</html>